//
//  UIImageView+Extension.swift
//  新浪微博
//
//  Created by MBP on 16/5/14.
//  Copyright © 2016年 MBP. All rights reserved.
//

import UIKit
import SDWebImage


extension UIImageView {
    
    convenience init(pn_imageName imageName: String) {
        self.init(image: UIImage(named: imageName))
    }
    
    //设置图像
    func pn_setImageWithURL(
        urlString: String?,
        placeholderName: String?,
        size: CGSize = CGSizeZero,
        isCorner: Bool = false,
        backColor: UIColor? = UIColor.whiteColor()) {
        
        // 占位图像
        var placeholderImage: UIImage?
        
        if placeholderName != nil {
            placeholderImage = UIImage(named: placeholderName!)
        }
        
        // 如果 url 为 nil
        guard let urlString = urlString,
            let url = NSURL(string: urlString) else {
                // 如果 urlString 为nil，但是指定了占位图像，显示占位图像
                image = placeholderImage
                
                return
        }
        
        //判断裁剪尺寸
        if size == CGSizeZero {
            sd_setImageWithURL(url, placeholderImage: placeholderImage)
            return
        }
        
        // 对图像进行裁切，提示：从网络不一定能够获取到图像
        sd_setImageWithURL(url, placeholderImage: placeholderImage) { (image, _, _, _) -> Void in
            
            // 1. 判断图像是否存在，如果没有图像直接返回
            guard let image = image else {
                return
            }
            
            // 2. 对图像进行裁切
            image.pn_asyncDrawImage(size, isCorner: isCorner, backColor: backColor) { (image) -> () in
                self.image = image
            }
        }

        
    }

}